package me.chyxion.spring.ext;

import java.util.HashMap;
import java.util.Map;
import me.chyxion.spring.ext.utils.ResponseTool;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/**
 * process return map
 * @version 0.0.2
 * @since 0.0.1
 * @author Shaun Chyxion <br />
 * chyxion@163.com <br />
 * Jun 25, 2014 9:00:57 PM
 */
@Aspect
public class BaseControllerAspect {
	private static final Log log = LogFactory.getLog(BaseControllerAspect.class);

    /**
     * Class Within <code>@Controller</code>,
     * And Without <code>@ResponseBody</code>
     */
    @Pointcut("within(@org.springframework.stereotype.Controller *) && !within(@org.springframework.web.bind.annotation.ResponseBody *)")
    public void controllerBean() {}

    /**
     * Method Within <code>@RequestMapping</code>,
     * Returns Map,
     * Without <code>@ResponseBody</code>
     */
    @Pointcut("execution(@org.springframework.web.bind.annotation.RequestMapping public java.util.Map *(..)) && !@annotation(org.springframework.web.bind.annotation.ResponseBody)")
    public void methodPointcut() {}

    @AfterReturning(pointcut = "controllerBean() && methodPointcut()", returning= "result")
    public void afterReturning(JoinPoint jp, Object result) {
		log.debug("Controller Aspect After Map Returning.");
		@SuppressWarnings("unchecked")
		Map<String, Object> mapRtn = (Map<String, Object>) result;
		Map<String, Object> mapData = new HashMap<String, Object>(mapRtn);
		mapRtn.clear();
		mapRtn.put(ResponseTool.MARK_DATA, true);
		mapRtn.put("data", mapData);
    }
}